#ifndef COOLPOOL_GLTEXTURE_H_
#define COOLPOOL_GLTEXTURE_H_

#include <iostream>
#include <GL/freeglut.h>
#include <FreeImage.h>

// Loads OpenGL texture from given path. If it was not able to load it, it return 0.
GLuint glLoadTexture(const char * path)
{
	FREE_IMAGE_FORMAT img_format = FIF_UNKNOWN;

	img_format = FreeImage_GetFileType(path, 0);
	if (img_format == FIF_UNKNOWN)
	{
		img_format = FreeImage_GetFIFFromFilename(path);
	}

	FIBITMAP * image;
	if ((img_format != FIF_UNKNOWN) && FreeImage_FIFSupportsReading(img_format))
	{
		image = FreeImage_Load(img_format, path);
	}
	else
	{
		std::cout << "Uknown format of texture: " << path << std::endl;
		return 0;
	}

	// Check if it was loaded.
	if (image)
	{
		image = FreeImage_ConvertTo32Bits(image);

		int w = FreeImage_GetWidth(image);
		int h = FreeImage_GetHeight(image);

		GLubyte* texture_base = new GLubyte[4 * w * h];
		char* pixels = (char*) FreeImage_GetBits(image);

		for (int j = 0; j < w * h; j++)
		{
			texture_base[j * 4 + 0] = pixels[j * 4 + 2];
			texture_base[j * 4 + 1] = pixels[j * 4 + 1];
			texture_base[j * 4 + 2] = pixels[j * 4 + 0];
			texture_base[j * 4 + 3] = pixels[j * 4 + 3];
		}

		//Now generate the OpenGL texture.
		GLuint texture_id;
		glGenTextures(1, &texture_id);
		glBindTexture(GL_TEXTURE_2D, texture_id);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, (GLvoid*) texture_base);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
		FreeImage_Unload(image);

		delete[] texture_base;
		return texture_id;
	}
	else
	{
		std::cout << "Failed to load texture: " << path << std::endl;
		return 0;
	}
}

#endif
